/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-9-22 上午11:39 Created by dwzhang
 */
package com.jade.bss.weixin.api.protocol.json;

import java.io.File;
import java.io.InputStream;

import com.jade.bss.weixin.WeixinApi;
import com.jade.bss.weixin.WeixinException;
import com.jade.framework.base.ErrorConstants;
import com.jade.framework.base.util.HttpUtils;

/**
 * 采用Xml方式的API。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a> 
 * @version 1.0 15-9-22 上午11:39
 */
public abstract class JsonApi
        extends WeixinApi
{
    protected <T extends Response> T post(String url, Object request, Class responseClass)
            throws WeixinException
    {
        try {
            T response = HttpUtils.postJsonHttp(url, request, responseClass);
            handle(response);
            return response;
        }
        catch (WeixinException e) {
            throw e;
        }
        catch (Exception e) {
            throw new WeixinException(ErrorConstants.ERR_NETWORK, "http error", e);
        }
    }

    protected <T extends Response> T postFile(String url, String name, File file, Class resposneClass)
            throws WeixinException
    {
        try {
            T response = HttpUtils.postFile(url, name, file, resposneClass);
            handle(response);
            return response;
        }
        catch (WeixinException e) {
            throw e;
        }
        catch (Exception e) {
            throw new WeixinException(ErrorConstants.ERR_NETWORK, "http error", e);
        }
    }

    protected <T extends Response> T postFile(String url, String name, InputStream in, String mimeType, String fileName,
                                              Class resposneClass)
            throws WeixinException
    {
        try {
            T response = HttpUtils.postFile(url, name, in, mimeType, fileName, resposneClass);
            handle(response);
            return response;
        }
        catch (WeixinException e) {
            throw e;
        }
        catch (Exception e) {
            throw new WeixinException(ErrorConstants.ERR_NETWORK, "http error", e);
        }
    }

    protected <T extends Response> T get(String url, Class responseClass)
            throws WeixinException
    {
        try {
            T response = HttpUtils.getHttp(url, responseClass);
            handle(response);
            return response;
        }
        catch (WeixinException e) {
            throw e;
        }
        catch (Exception e) {
            throw new WeixinException(ErrorConstants.ERR_NETWORK, "http error", e);
        }
    }

    protected void handle(Response response)
            throws WeixinException
    {
        if (!response.isOK()) {
            throw new WeixinException("err.bss.weixin.api.server",
                    response.getErrorCode() + ":" + response.getErrorMsg());
        }
    }
}
